import { createStore } from 'vuex'
import { handleResult } from '../helpers/utils'
import { characterService, userService } from '../services'
import { getCharacterInfoById } from '../helpers/character'

export default createStore({
  state: {
    characterInfo: [],
    userInfo: {},
    userCharacter: {}
  },
  mutations: {
    setCharacterInfo (state, characterInfo) {
      state.characterInfo = characterInfo
    },
    setUserInfo (state, userInfo) {
      state.userInfo = userInfo
    },
    setUserCharacter (state, userCharacter) {
      state.userCharacter = userCharacter
    }
  },
  actions: {
    async getCharacterInfo (store) {
      const res = await characterService.getCharacterlist()
      handleResult(res).success(({ data }) => {
        store.commit('setCharacterInfo', data)
      })
    },
    async getUserInfo (store) {
      const res = await userService.getInfo()
      handleResult(res).success(({ data }) => {
        store.commit('setUserInfo', data)
        store.commit('setUserCharacter', getCharacterInfoById(data.character))
      })
    }
  }
})
